import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Drawer, Form, Input, Select, Space, Tabs, message } from 'antd';
import { SaveOutlined, PlayCircleOutlined, EyeOutlined, DownloadOutlined, UploadOutlined } from '@ant-design/icons';

// BPMN相关导入
import BpmnModeler from 'bpmn-js/lib/Modeler';
import BpmnViewer from 'bpmn-js/lib/Viewer';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import { workflowService } from '../services/workflowService';

interface ProcessDesignerProps {
  processId?: string;
  templateXml?: string;
  readonly?: boolean;
  onSave?: (bpmnXml: string, processName: string) => void;
  onDeploy?: (bpmnXml: string, processName: string) => void;
}

interface ProcessElement {
  id: string;
  name: string;
  type: string;
  properties: Record<string, any>;
}

const ProcessDesigner: React.FC<ProcessDesignerProps> = ({
  processId,
  templateXml,
  readonly = false,
  onSave,
  onDeploy
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const modelerRef = useRef<any>(null);
  const [selectedElement, setSelectedElement] = useState<ProcessElement | null>(null);
  const [propertiesVisible, setPropertiesVisible] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [processXml, setProcessXml] = useState<string>('');
  const [processName, setProcessName] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [nameForm] = Form.useForm();

  // 默认BPMN模板
  const defaultBpmnXml = `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="5.0.0">
  <bpmn:process id="Process_1" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" />
  </bpmn:process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_1">
    <bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="Process_1">
      <bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="StartEvent_1">
        <dc:Bounds x="179" y="79" width="36" height="36" />
      </bpmndi:BPMNShape>
    </bpmndi:BPMNPlane>
  </bpmndi:BPMNDiagram>
</bpmn:definitions>`;

  // 初始化BPMN建模器
  useEffect(() => {
    if (!containerRef.current) return;

    const modeler = new BpmnModeler({
      container: containerRef.current,
      keyboard: {
        bindTo: window
      }
    });

    modelerRef.current = modeler;

    // 监听元素选择事件
    modeler.on('selection.changed', (event: any) => {
      const { newSelection } = event;
      if (newSelection.length > 0) {
        const element = newSelection[0];
        setSelectedElement({
          id: element.id,
          name: element.businessObject.name || '',
          type: element.type,
          properties: element.businessObject
        });
        setPropertiesVisible(true);
      } else {
        setSelectedElement(null);
        setPropertiesVisible(false);
      }
    });

    // 加载默认流程
    loadProcess(defaultBpmnXml);

    return () => {
      // 清理资源
      if (modelerRef.current) {
        modelerRef.current.destroy();
      }
    };
  }, []);

  // 根据processId或templateXml加载BPMN数据
  useEffect(() => {
    if (processId) {
      const loadProcessDefinition = async () => {
        try {
          setLoading(true);
          const processDefinition = await workflowService.getProcessDefinition(processId);
          if (processDefinition) {
            const xml = await workflowService.getProcessDefinitionXml(processId);
            loadProcess(xml);
            setProcessName(processDefinition.name || '');
            nameForm.setFieldsValue({ processName: processDefinition.name || '' });
          }
        } catch (error) {
          console.error('加载流程定义失败:', error);
          message.error('加载流程定义失败');
        } finally {
          setLoading(false);
        }
      };

      loadProcessDefinition();
    } else if (templateXml) {
      // 从模板加载
      loadProcess(templateXml);
      setProcessName('新建流程');
      nameForm.setFieldsValue({ processName: '新建流程' });
    }
  }, [processId, templateXml]);

  // 加载流程
  const loadProcess = async (xml: string) => {
    if (!modelerRef.current) return;

    try {
      setLoading(true);
      await modelerRef.current.importXML(xml);
      setProcessXml(xml);
      message.success('流程加载成功');
    } catch (error) {
      console.error('流程加载失败:', error);
      message.error('流程加载失败');
    } finally {
      setLoading(false);
    }
  };

  // 保存流程
  const handleSave = async () => {
    if (!modelerRef.current || !processName.trim()) {
      message.error('请先输入流程名称');
      return;
    }

    try {
      setLoading(true);
      const { xml } = await modelerRef.current.saveXML({ format: true });
      
      onSave?.(xml, processName.trim());
      message.success('流程保存成功');
    } catch (error) {
      console.error('流程保存失败:', error);
      message.error('流程保存失败');
    } finally {
      setLoading(false);
    }
  };

  // 部署流程
  const handleDeploy = async () => {
    if (!modelerRef.current || !processName.trim()) {
      message.error('请先输入流程名称');
      return;
    }

    try {
      setLoading(true);
      const { xml } = await modelerRef.current.saveXML({ format: true });
      
      onDeploy?.(xml, processName.trim());
      message.success('流程部署成功');
    } catch (error) {
      console.error('流程部署失败:', error);
      message.error('流程部署失败');
    } finally {
      setLoading(false);
    }
  };

  // 预览流程
  const handlePreview = () => {
    setPreviewVisible(true);
  };

  // 导出流程
  const handleExport = async () => {
    if (!modelerRef.current) return;

    try {
      const { xml } = await modelerRef.current.saveXML({ format: true });
      
      const blob = new Blob([xml], { type: 'application/xml' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `process_${Date.now()}.bpmn`;
      a.click();
      URL.revokeObjectURL(url);
      
      message.success('流程导出成功');
    } catch (error) {
      console.error('流程导出失败:', error);
      message.error('流程导出失败');
    }
  };

  // 导入流程
  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.bpmn,.xml';
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (event) => {
          const xml = event.target?.result as string;
          loadProcess(xml);
        };
        reader.readAsText(file);
      }
    };
    input.click();
  };

  // 更新元素属性
  const handleUpdateProperties = (values: any) => {
    if (!selectedElement || !modelerRef.current) return;

    try {
      // const modeling = modelerRef.current.get('modeling');
      // const elementRegistry = modelerRef.current.get('elementRegistry');
      // const element = elementRegistry.get(selectedElement.id);
      
      // if (element) {
      //   modeling.updateProperties(element, values);
      //   message.success('属性更新成功');
      // }
      
      // 临时实现
      message.success('属性更新成功（临时实现）');
    } catch (error) {
      console.error('属性更新失败:', error);
      message.error('属性更新失败');
    }
  };

  return (
    <div className="process-designer" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 工具栏 */}
      <Card size="small" style={{ marginBottom: 8 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Form form={nameForm} layout="inline" style={{ flex: 1, marginRight: 16 }}>
            <Form.Item 
              name="processName" 
              label="流程名称"
              rules={[{ required: true, message: '请输入流程名称' }]}
              style={{ marginBottom: 0 }}
            >
              <Input 
                placeholder="请输入流程名称"
                value={processName}
                onChange={(e) => setProcessName(e.target.value)}
                disabled={readonly}
                style={{ width: 200 }}
              />
            </Form.Item>
          </Form>
          
          <Space>
            <Button 
              type="primary" 
              icon={<SaveOutlined />} 
              onClick={handleSave}
              loading={loading}
              disabled={readonly}
            >
              保存
            </Button>
            <Button 
              icon={<PlayCircleOutlined />} 
              onClick={handleDeploy}
              loading={loading}
              disabled={readonly}
            >
              部署
            </Button>
            <Button 
              icon={<EyeOutlined />} 
              onClick={handlePreview}
            >
              预览
            </Button>
            <Button 
              icon={<DownloadOutlined />} 
              onClick={handleExport}
            >
              导出
            </Button>
            <Button 
              icon={<UploadOutlined />} 
              onClick={handleImport}
              disabled={readonly}
            >
              导入
            </Button>
          </Space>
        </div>
      </Card>

      {/* 主要内容区域 */}
      <div style={{ flex: 1, display: 'flex' }}>
        {/* BPMN画布 */}
        <div style={{ flex: 1, position: 'relative' }}>
          <div 
            ref={containerRef} 
            style={{ width: '100%', height: '100%' }}
          />
        </div>
      </div>

      {/* 属性面板抽屉 */}
      <Drawer
        title="元素属性"
        placement="right"
        width={400}
        open={propertiesVisible}
        onClose={() => setPropertiesVisible(false)}
        destroyOnClose
      >
        {selectedElement && (
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              name: selectedElement.name,
              id: selectedElement.id,
              type: selectedElement.type
            }}
            onFinish={handleUpdateProperties}
          >
            <Form.Item label="元素ID" name="id">
              <Input disabled />
            </Form.Item>
            
            <Form.Item label="元素类型" name="type">
              <Input disabled />
            </Form.Item>
            
            <Form.Item label="名称" name="name">
              <Input placeholder="请输入元素名称" />
            </Form.Item>
            
            {selectedElement.type === 'bpmn:UserTask' && (
              <>
                <Form.Item label="审批人" name="assignee">
                  <Select
                    placeholder="请选择审批人"
                    options={[
                      { label: '张三', value: 'zhangsan' },
                      { label: '李四', value: 'lisi' },
                      { label: '王五', value: 'wangwu' }
                    ]}
                  />
                </Form.Item>
                
                <Form.Item label="表单绑定" name="formKey">
                  <Select
                    placeholder="请选择绑定表单"
                    options={[
                      { label: '请假申请表', value: 'leave_form' },
                      { label: '报销申请表', value: 'expense_form' },
                      { label: '采购申请表', value: 'purchase_form' }
                    ]}
                  />
                </Form.Item>
              </>
            )}
            
            {selectedElement.type === 'bpmn:ExclusiveGateway' && (
              <Form.Item label="条件表达式" name="conditionExpression">
                <Input.TextArea 
                  placeholder="请输入条件表达式，如：${amount > 1000}"
                  rows={3}
                />
              </Form.Item>
            )}
            
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  更新属性
                </Button>
                <Button onClick={() => setPropertiesVisible(false)}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        )}
      </Drawer>

      {/* 预览抽屉 */}
      <Drawer
        title="流程预览"
        placement="right"
        width={800}
        open={previewVisible}
        onClose={() => setPreviewVisible(false)}
      >
        <div style={{ height: '100%', border: '1px solid #d9d9d9' }}>
          {/* 这里将显示只读的BPMN查看器 */}
          <div style={{
            width: '100%',
            height: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#999'
          }}>
            流程预览区域（待bpmn-js依赖安装后启用）
          </div>
        </div>
      </Drawer>
    </div>
  );
};

export default ProcessDesigner;